import {
	createSSRApp
} from "vue";

import App from "./App.vue";
import axios from 'axios'
import settleAxios from 'axios/lib/core/settle'
import buildURLAxios from "axios/lib/helpers/buildURL"
import * as Pinia from 'pinia';
import { authInterceptor } from './directives/intercept'; // 引入指令



uni.setStorageSync("Authorization",null)
// 解决uniapp 适配axios请求，避免报adapter is not a function错误
axios.defaults.adapter = config => {
	return new Promise((resolve, reject) => {
		let settle = settleAxios
		let buildURL = buildURLAxios
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				// console.log("执行完成：", response)
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}


const interceptors = () => {
    uni.addInterceptor('navigateTo', {
        invoke: (e) => {
            console.log(e);
            
            const excludeUrl = ['/pages/home/home', '/pages/team/team', '/pages/person/person']; // 不拦截的页面路由
            const index = excludeUrl.findIndex(item => item === e.url); // 检查当前URL是否在不拦截列表中
            const Authorization = uni.getStorageSync("Authorization");
            console.log("Authorization", Authorization);
            
            // 仅当用户未登录且页面不在排除列表时进行拦截
            if (Authorization === null && index === -1) {
                uni.switchTab({
                    url: "/pages/person/person",
                    success: () => {
                        uni.showToast({
                            title: '请先登录',
                            icon: 'none'
                        });
                    }
                });
                // 阻止进一步的跳转操作
                return false;
            }
            console.log("跳转前拦截", e);
        }
    });
};


// config = {

// }
export function createApp() {
    const app = createSSRApp(App);
    app.config.globalProperties.$checkLogin=()=>{
        if(uni.getStorageSync("Authorization")===null){
            uni.showToast({
              title:'请登录',
              icon:'none'
            })
            uni.switchTab({
              url:'/pages/person/person'
            })
            return false
          }
    }
    app.use(Pinia.createPinia());
    app.use(interceptors());
    app.directive('authInterceptor', authInterceptor);
    return {
        app,
        Pinia,
    };
}


 
 
 

